package com.castle.releasedemo;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.json.JSONObject;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.castle.utils.SecretSignUtils.calcSign;

/**
 * 秘钥对签名示例 GET请求
 * @author openapi
 */
public class SecretSignGetDemo {


	public static void main(String[] args) throws UnsupportedEncodingException {
		String paramEncryptKey="参数秘钥(自己设置的16位秘钥)";
		SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, paramEncryptKey.getBytes());
		//该接口需要的密钥Id
		String secretId = "秘钥管理中的SecretId";
		//该接口需要的密钥Key
		String secretKey = "秘钥管理中的SecretKey";
		//用户中心-账号信息-APPID
		String appId="用户信息的APPID";


		String datetime = DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN);
		System.out.println(datetime);

		// 请求头
		Map<String, String> headers = new HashMap<>();
		headers.put("C-Date", datetime);
		headers.put("C-Appid", appId);
		headers.put("C-Serial", "");//此处自行生成唯一的流水号标识  本次请求的流水号（请求的唯一标识），不参与签名
		//支持 application/json 与 multipart/form-data
		headers.put("Content-Type", "application/json;charset=utf-8");
		headers.put("C-Secret",secretId);

		// 查询参数 根据实际情况调整
		Map<String, String> queryParams = new HashMap<>();
		queryParams.put("city", "朝阳");
		queryParams.put("needday", "1");
		queryParams.put("prov", "北京");


		Map<String,Object> signMap=new HashMap<>();
		signMap.putAll(queryParams);

		// 签名
		String sign = calcSign(secretId, secretKey, datetime,signMap);
		headers.put("Sign",sign);
		System.out.println(sign);

		// 接口的url地址
		StringBuilder url = new StringBuilder("API接口地址");

		//拼接queryParam
		if(!queryParams.isEmpty()){
			url.append("?");
			for(String paramKey:queryParams.keySet()){
				url.append(paramKey+"="+aes.encryptHex(queryParams.get(paramKey))+"&");
			}
		}
		//发送请求
		OkHttpClient okHttpClient = new OkHttpClient();
		Request.Builder requestBuilder=new Request.Builder().url(url.toString());
		for(String headerKey:headers.keySet()){
			requestBuilder.addHeader(headerKey,headers.get(headerKey));
		}
		Request request=requestBuilder.build();
		try {
			final Call call = okHttpClient.newCall(request);
			Response response = call.execute();
			System.out.println(new JSONObject(response.body().string()));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}


}

